import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

///  所有单选drawer约束模型
abstract class AbstractRequestFormSelectDrawer {
  final BaseHttpRequestModel request;

  final dynamic dataSource;

  final Function(String key, dynamic value) onRadioItemPress;

  AbstractRequestFormSelectDrawer({@required this.request, this.dataSource, this.onRadioItemPress});
}

/// 基本单选AbstractRequestFormSelectDrawer
class RequestFormSelectDrawer extends StatefulWidget implements AbstractRequestFormSelectDrawer {
  RequestFormSelectDrawer({Key key, @required this.request, this.dataSource, this.onRadioItemPress}) : super(key: key);

  final BaseHttpRequestModel request;

  final dynamic dataSource;

  final Function(String key, dynamic value) onRadioItemPress;

  @override
  _RequestFormSelectDrawerState createState() => _RequestFormSelectDrawerState();
}

class _RequestFormSelectDrawerState extends State<RequestFormSelectDrawer> {
  String _service;

  String _radioSelect;

  @override
  void initState() {
    this._service = BaseTransformUtil.matchServiceUrl(widget.request.inputApi, widget.dataSource);
    this._radioSelect = BaseUtils.getKeyData(widget.dataSource, widget.request.fieldName).toString();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseRefreshComponent(
      path: _service,
      method: BaseHttpMethodEnum.GET,
      separatorBuilder: (item) => BaseComponentUtils.buildHorizontalDivider(),
      buildItem: (Map<String, dynamic> item, int index) => _buildRadioListItem(context, item, index),
      isPaging: false,
    );
  }

  Widget _buildRadioListItem(BuildContext context, Map<String, dynamic> item, int index) {
    String key = BaseUtils.getKeyData(item, 'key').toString();
    String value = BaseUtils.getKeyData(item, 'value').toString();
    return RadioListTile(
      title: Text(value, style: Theme.of(context).textTheme.bodyText2),
      value: key,
      groupValue: _radioSelect,
      onChanged: (dynamic selected) {
        setState(() {
          _radioSelect = selected;
        });
        widget.onRadioItemPress(key, value);
      },
    );
  }
}
